package com.ruoyi.web.controller.hedianzhan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.math.BigDecimal;

/**
 * HeDianZhanController
 *
 * @author ruoyi
 * @date 2021-10-29
 */

@CrossOrigin(originPatterns = "*", allowCredentials = "true", allowedHeaders = "*", methods = {})
@Controller
@ResponseBody
@RequestMapping("/hedianzhan")
public class HeDianZhanController extends BaseController {

    @Autowired
    private ISQuestionsService sQuestionsService;
    @Autowired
    private IEstimatedEventService estimatedEventService;
    @Autowired
    private IOverhaulLibraryService overhaulLibraryService;
    @Autowired
    private ISDictionaryService sDictionaryService;
    @Autowired
    private ISEstimatedJudgeService estimatedJudgeService;
    @Autowired
    private ISImagesService imagesService;
    @Autowired
    private ITrafficRecordService trafficRecordService;
    @Autowired
    private IPsEmplastyeardoseService IPsEmplastyeardoseService;
    @Autowired
    private IDoseValueService IDoseValueService;
    @Autowired
    ISEstimatedJudgeService iSEstimatedJudgeService;
    @Autowired
    IOverhaulStageService iOverhaulStageService;
    @Autowired
    IDoseValueMonitorService iDoseValueMonitorService;
    @Autowired
    IWorkOrderNameDoseValueService iWorkOrderNameDoseValueService;
    @Autowired
    ISpecialTemplateService iSpecialTemplateService;
    @Autowired
    ISpecialMonitoringService iSpecialMonitoringService;
    @Autowired
    ISQuestionsDiscussService iSQuestionsDiscussService;
    @Autowired
    ISQuestionsDiscussReplayService iSQuestionsDiscussReplayService;


    @RequestMapping("/myMainPage")
    public String myMainPage(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String mobile = (String) json.get("mobile");
//        TrafficRecord trafficRecord = new TrafficRecord();
//        trafficRecord.setDtmsContacts(mobile);
        TrafficRecord trafficRecord = trafficRecordService.getUserDoseValueByUserId(mobile);
        BigDecimal rp_dosevalue = BigDecimal.valueOf(0);// 当前剂量
        String name = "无";// 当前剂量
        String company = "无";// 当前剂量
        String PS_EMPID = "";// 当前剂量
        String isManager = "N";// 当前剂量
        BigDecimal psyd_lastyeardose = BigDecimal.valueOf(0);
        int monthTimes = 0;// 当前剂量
        long hours = 0;

        JSONObject jo_back = new JSONObject();
        if (null == trafficRecord) {
            jo_back.put("name", "无");
            jo_back.put("company", "无");
            jo_back.put("PS_EMPID", "无");
            jo_back.put("isManager", "N");
            jo_back.put("mytimes", new JSONArray());
            jo_back.put("mydose", new JSONArray());
            jo_back.put("yeardose", "无");
            jo_back.put("nowdose", "无");
            jo_back.put("monthTimes", "无");
            jo_back.put("monthTimesLong", hours);
            jo_back.put("alldose", "/");
        } else {
            PS_EMPID = trafficRecord.getPsEmpid();// 员工id
            name = trafficRecord.getPsWorkName();// 员工姓名
            company = trafficRecord.getCOMPANY();// 员工公司
            isManager = trafficRecord.getIsManager();// 员工公司
            // 判断RP_PAUSE_DATE和PS_END_DATE都为空，则显示rp_dosevalue，有一个不为空则显示文字无
            Date RP_PAUSE_DATE = trafficRecord.getRpPauseDate();
            Date PS_END_DATE = trafficRecord.getPsEndDate();
            if ("".equals(RP_PAUSE_DATE) && "".equals(PS_END_DATE)) {
                rp_dosevalue = trafficRecord.getRpDosevalue();// 当前剂量
            }
            // 2
            PsEmplastyeardose psEmplastyeardose = new PsEmplastyeardose();
            psEmplastyeardose.setPsydEmpcnname(mobile);
            psEmplastyeardose = IPsEmplastyeardoseService.getByUserId(psEmplastyeardose);
            if (null != psEmplastyeardose) {
                psyd_lastyeardose = psEmplastyeardose.getPsydLastyeardose();// 个人年剂量
            }

            // 3
            DoseValue doseValue = new DoseValue();
            doseValue.setDvEmpid(Long.valueOf(PS_EMPID));
            List<DoseValue> dvs = IDoseValueService.getNumberTimesByMonthForUser(doseValue);// 次数列表

            // 4
            DoseValue doseValue1 = new DoseValue();
            doseValue1.setDvEmpid(Long.valueOf(PS_EMPID));
            List<DoseValue> dvs1 = IDoseValueService.getDVVALUEByMonthForUser(doseValue1);// 剂量列表

            // 5
            DoseValue doseValue2 = new DoseValue();
            doseValue2.setDvEmpid(Long.valueOf(PS_EMPID));
            doseValue2 = IDoseValueService.getNumberTimesThisMonthForUser(doseValue2);
            monthTimes = doseValue2.getCount();// 当月次数

            // 6
            DoseValue doseValue3 = new DoseValue();
            doseValue3.setDvEmpid(Long.valueOf(PS_EMPID));
            doseValue3 = IDoseValueService.getTimesLongThisMonthForUser(doseValue3);

            int monthTimesLong = doseValue3.getCount();// 当月工时
            if (monthTimesLong > 0) {
                hours = (monthTimesLong % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            }

            jo_back.put("name", name);
            jo_back.put("company", company);
            jo_back.put("PS_EMPID", PS_EMPID);
            jo_back.put("isManager", isManager);
            jo_back.put("mytimes", dvs);
            jo_back.put("mydose", dvs1);
            jo_back.put("yeardose", psyd_lastyeardose);
            jo_back.put("nowdose", rp_dosevalue);
            jo_back.put("monthTimes", monthTimes);
            jo_back.put("monthTimesLong", hours);
            jo_back.put("alldose", "/");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        hs.put("backStr", jo_back);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    //  重要反馈列表
    @RequestMapping("/getQuestionImports")
    public String getQuestionImports(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String theme = (String) json.get("question");
        String isManager = (String) json.get("isManager");
        int pageNumber = (Integer) json.get("pageNumber");
        int lines = (Integer) json.get("lines");
        int count = 0;
        List<EstimatedEvent> list = new ArrayList();
        if ("Y".equals(isManager)) {
            count = estimatedEventService.getAllImportCount2(theme);
            list = estimatedEventService.getAllImport2(pageNumber, lines, theme);
        } else {
            // 仅通过审核及一般事件
            count = estimatedEventService.getAllImportCount(theme);
            list = estimatedEventService.getAllImport(pageNumber, lines, theme);
        }
        hs.put("DBList", list);
        hs.put("DBAccount", count);
        return objectMapper.writeValueAsString(hs);
    }

    //  重要反馈审核
    @RequestMapping("/QuestionExamine")
    public String QuestionExamine(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String id = (Integer) json.get("id") + "";
        String statuss = (String) json.get("statuss");
        iSEstimatedJudgeService.uptStatussById(id, statuss);
        return objectMapper.writeValueAsString(hs);

    }


    //  专项监控
    @RequestMapping("/specialMainPage")
    public String specialMainPage(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String current_overhaul = (String) json.get("current_overhaul");// 当前大修
        String reference_overhaul = (String) json.get("reference_overhaul");// 参考大修

        // 专项递归表
        List<SpecialTemplate> list0 = iSpecialTemplateService.getChildrens();
//        JSONArray ja16 = JSONArray.parseArray(rb.dealBack);

//当前大修的专项信息、工期信息
//		JSONObject jo1 = new JSONObject();
//		jo1.put("current_overhaul", current_overhaul);
//		rb.rbb.requestBusiness = "special_monitoring_select_getAllByOverhaul";
//		rb.rbb.requestBusinessParameter = jo1;// "需要你自定义的JSONObject格式的参数";
//		rb = rb.ba.operateDB(rb);
//		String current_overhaul_info = rb.dealBack;

        // 专项按分类统计doseValue
        // 专项按分类统计doseValue
        List<SpecialMonitoring> list1 = iSpecialMonitoringService.getDoseValueByOverhaul(current_overhaul);
//        JSONArray ja17 = JSONArray.parseArray(rb.dealBack);

        JSONArray current_overhaul_info = new JSONArray();
        // 加起来
        if (list0 != null) {
            Long id = Long.valueOf(0);
            String childrens = "";
            for (int i = 0; i < list0.size(); i++) {
                JSONObject josi = new JSONObject();
                SpecialTemplate tm = list0.get(i);
                childrens = tm.getChildrens();
                id = tm.getId();
                BigDecimal dose_value1 = BigDecimal.valueOf(0);
                Long work_time1 = Long.valueOf(0);
                double orderno_number1 = 0;
                String level0_name = tm.getSpecialName();
                // 专项柱状图
                for (int j = 0; j < list1.size(); j++) {
                    SpecialMonitoring sm = list1.get(j);
                    Long graded_to2 = sm.getGradedTo();
                    BigDecimal dose_value2 = sm.getDoseValue();
                    String orderno_number = sm.getOrdernoNumber();
                    Long work_time = sm.getWorkTime();
                    if (id == graded_to2) {
                        dose_value1 = dose_value1.add(dose_value2);
                        work_time1 += work_time;
                        BigDecimal b11 = new BigDecimal(Double.toString(orderno_number1));
                        BigDecimal b21 = new BigDecimal(orderno_number);
                        orderno_number1 = b11.add(b21).doubleValue();
                    } else {
                        if (childrens != null) {
                            String[] cs = childrens.split(",");
                            if (Arrays.binarySearch(cs, graded_to2 + "") >= 0) {
                                dose_value1 = dose_value1.add(dose_value2);
                                work_time1 += work_time;
                                BigDecimal b11 = new BigDecimal(Double.toString(orderno_number1));
                                BigDecimal b21 = new BigDecimal(orderno_number);
                                orderno_number1 = b11.add(b21).doubleValue();
                            }
                        }
                    }
//					if (childrens.contains(graded_to2) || id.equals(graded_to2)) {
////						jas.add(job);
//						BigDecimal b1 = new BigDecimal(Double.toString(dose_value1));
//						BigDecimal b2 = new BigDecimal(dose_value2);
//						dose_value1 = b1.add(b2).doubleValue();
//						work_time1 += Integer.parseInt(work_time);
//						BigDecimal b11 = new BigDecimal(Double.toString(orderno_number1));
//						BigDecimal b21 = new BigDecimal(orderno_number);
//						orderno_number1 = b11.add(b21).doubleValue();
//					}
                }
                josi.put("special_name", level0_name);
                josi.put("work_time", work_time1);
                josi.put("orderno_number", orderno_number1);
                josi.put("dose_value", dose_value1);
                current_overhaul_info.add(josi);
            }
        }

//参考大修的专项信息、工期信息
//		JSONObject jo2 = new JSONObject();
//		jo2.put("current_overhaul", reference_overhaul);
//		rb.rbb.requestBusiness = "special_monitoring_select_getAllByOverhaul";
//		rb.rbb.requestBusinessParameter = jo2;// "需要你自定义的JSONObject格式的参数";
//		rb = rb.ba.operateDB(rb);
//		String reference_overhaul_info = rb.dealBack;

        JSONArray reference_overhaul_info = new JSONArray();
        if (!"".equals(reference_overhaul)) {
            List<SpecialMonitoring> list2 = iSpecialMonitoringService.getDoseValueByOverhaul(reference_overhaul);
//            JSONArray ja18 = JSONArray.parseArray(rb.dealBack);

            // 加起来
            if (list0.size() > 0) {
                String childrens = "";
                Long id = Long.valueOf(0);
                for (int i = 0; i < list0.size(); i++) {
                    JSONObject josi = new JSONObject();
                    SpecialTemplate tm = list0.get(i);
                    childrens = tm.getChildrens();
                    id = tm.getId();
                    BigDecimal dose_value1 = BigDecimal.valueOf(0);
                    Long work_time1 = Long.valueOf(0);
                    double orderno_number1 = 0;
                    String level0_name = tm.getSpecialName();
                    // 专项柱状图
                    for (int j = 0; j < list2.size(); j++) {
                        SpecialMonitoring sm = list1.get(j);
                        Long graded_to2 = sm.getGradedTo();
                        BigDecimal dose_value2 = sm.getDoseValue();
                        String orderno_number = sm.getOrdernoNumber();
                        Long work_time = sm.getWorkTime();

                        if (id == graded_to2) {
                            dose_value1 = dose_value1.add(dose_value2);
                            work_time1 += work_time;
                            BigDecimal b11 = new BigDecimal(Double.toString(orderno_number1));
                            BigDecimal b21 = new BigDecimal(orderno_number);
                            orderno_number1 = b11.add(b21).doubleValue();
                        } else {
                            if (childrens != null) {
                                String[] cs = childrens.split(",");
                                if (Arrays.binarySearch(cs, graded_to2 + "") >= 0) {
                                    dose_value1 = dose_value1.add(dose_value2);
                                    work_time1 += work_time;
                                    BigDecimal b11 = new BigDecimal(Double.toString(orderno_number1));
                                    BigDecimal b21 = new BigDecimal(orderno_number);
                                    orderno_number1 = b11.add(b21).doubleValue();
                                }
                            }
                        }
                    }
                    josi.put("special_name", level0_name);
                    josi.put("work_time", work_time1);
                    josi.put("orderno_number", orderno_number1);
                    josi.put("dose_value", dose_value1);
                    reference_overhaul_info.add(josi);
                }
            }
        }
        hs.put("current_overhaul", current_overhaul_info);
        hs.put("reference_overhaul", reference_overhaul_info);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    // 专项监控
    @RequestMapping("/stageMainPage")
    public String stageMainPage(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String current_overhaul = (String) json.get("current_overhaul");
        String reference_overhaul = (String) json.get("reference_overhaul");
//当前大修的阶段信息、工期信息
        List<OverhaulStage> current_overhaul_info = iOverhaulStageService.getByOverhaul(current_overhaul);
        // 参考大修的阶段信息、工期信息
        List<OverhaulStage> reference_overhaul_info = new ArrayList();
        if (!"".equals(reference_overhaul)) {
            reference_overhaul_info = iOverhaulStageService.getByOverhaul(reference_overhaul);
        }
        hs.put("current_overhaul", current_overhaul_info);
        hs.put("reference_overhaul", reference_overhaul_info);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    // 剂量监测
    @RequestMapping("/doseValueMainPage")
    public String doseValueMainPage(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String overhaul_name = (String) json.get("current_overhaul");

//大修信息
        ;
        OverhaulLibrary overhaulLibrary = overhaulLibraryService.getByName(overhaul_name);
//        JSONObject jo1_b = JSON.parseObject(rb.dealBack);

//每日、累计的实际剂量和指标剂量
        int pageNumber = 0;
        int lines = 15;
        List<DoseValueMonitor> list0 = iDoseValueMonitorService.getByOverhaul(pageNumber, lines, overhaul_name);
//        JSONArray ja1 = JSONArray.parseArray(rb.dealBack);

        // 阶段列表
        List<OverhaulStage> list = iOverhaulStageService.getByOverhaul(overhaul_name);
//        JSONArray ja2 = JSONArray.parseArray(rb.dealBack);

        // 当前阶段
        String stage_name = "";
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                OverhaulStage os = list.get(i);
                if (!"".equals(os.getActuialStartTime()) && "".equals(os.getActuialEndTime())) {
                    // 查询它的parent_id的所有工单信息
                    stage_name = os.getCurrentStage();
                    break;
                }
            }
            if ("".equals(stage_name)) {
                OverhaulStage os = list.get(list.size() - 1);
                stage_name = os.getCurrentStage();
            }
        }

//开工率
        DoseValueMonitor dv = new DoseValueMonitor();
        dv.setOverhaulName(overhaul_name);
        dv.setStageName(stage_name);
        List<DoseValueMonitor> list1 = iDoseValueMonitorService.getDoing(dv);

        String stage_orderno_number = "0";
        String orderno_start_number = "0";
        // 今日剂量
        BigDecimal today_doseValue = BigDecimal.valueOf(0);
        // 昨日剂量
        BigDecimal today_doseValue_l = BigDecimal.valueOf(0);
        String changeType = "0";
        double changeValue = 0;
        double changeRate = 0;
        if (list1.size() > 0) {
            DoseValueMonitor dvm = list1.get(0);

            stage_orderno_number = dvm.getStageOrdernoNumber();//
            if (null == stage_orderno_number) {
                stage_orderno_number = "0";
            }
            orderno_start_number = dvm.getOrdernoStartNumber();//
            if (null == orderno_start_number) {
                orderno_start_number = "0";
            }
            // 今日剂量
            today_doseValue = dvm.getDailyRealTimeDoseValue();//
            if (null == today_doseValue) {
                today_doseValue = BigDecimal.valueOf(0);
            }

            if (list1.size() > 1) {
                // 剂量跟昨日比率
                DoseValueMonitor _dvm = list1.get(1);
                // 昨日剂量
                today_doseValue_l = _dvm.getDailyRealTimeDoseValue();//
                if (null == today_doseValue_l) {
                    today_doseValue_l = BigDecimal.valueOf(0);
                }
                if (today_doseValue.compareTo(today_doseValue_l) < 0) {
//			    System.out.println("第二位数大！");上升
                    changeType = "1";
                    changeValue = today_doseValue_l.subtract(today_doseValue).doubleValue();
                    BigDecimal b1 = new BigDecimal(changeValue);
                    changeRate = b1.divide(today_doseValue, 3, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                if (today_doseValue.compareTo(today_doseValue_l) == 0) {
//			    System.out.println("两位数一样大！");
                    changeType = "0";
                    changeRate = 0;
                }
                if (today_doseValue.compareTo(today_doseValue_l) > 0) {
//			    System.out.println("第一位数大！");下降
                    changeType = "2";
                    changeValue = today_doseValue.subtract(today_doseValue_l).doubleValue();
                    BigDecimal b1 = new BigDecimal(changeValue);
                    changeRate = b1.divide(today_doseValue, 3, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
            }
        }

        // 工单列表
        int pageNumber1 = 0;
        int lines1 = 10;
        List<WorkOrderNameDoseValue> list2 = iWorkOrderNameDoseValueService.getAll(pageNumber1, lines1, overhaul_name);
//        JSONArray ja5 = JSONArray.parseArray(rb.dealBack);

        // 专项递归表
        List<SpecialTemplate> list3 = iSpecialTemplateService.getChildrens();
//        JSONArray ja16 = JSONArray.parseArray(rb.dealBack);

        // 专项按分类统计doseValue
        List<SpecialMonitoring> list4 = iSpecialMonitoringService.getDoseValueByOverhaul(overhaul_name);
//        JSONArray ja17 = JSONArray.parseArray(rb.dealBack);

        // 剂量饼图
        JSONArray jas = new JSONArray();
        // 加起来
        if (list3.size() > 0) {
            String childrens = "";
            long id = 0;
            for (int i = 0; i < list3.size(); i++) {
                JSONObject josi = new JSONObject();
                SpecialTemplate st = list3.get(i);
                childrens = st.getChildrens();
                id = st.getId();
                BigDecimal dose_value1 = BigDecimal.valueOf(0);
                String level0_name = st.getSpecialName();
                for (int j = 0; j < list4.size(); j++) {
                    SpecialMonitoring sm = list4.get(j);
                    Long graded_to2 = sm.getGradedTo();
                    BigDecimal dose_value2 = sm.getDoseValue();
                    if (id == graded_to2) {
                        dose_value1 = dose_value1.add(dose_value2);
                    } else {
                        if (childrens != null) {
                            String[] cs = childrens.split(",");
                            if (Arrays.binarySearch(cs, graded_to2 + "") >= 0) {
                                dose_value1 = dose_value1.add(dose_value2);
                            }
                        }
                    }
                }
                josi.put("level0_name", level0_name);
                josi.put("dose_value", Double.toString(dose_value1.doubleValue()));
                jas.add(josi);
            }
            jas = jsonArraySort(jas, "dose_value", false);
        }

//		// 事件反馈总数
//		rb.rbb.requestBusiness = "s_questions_select_getTargetCount";
//		rb.rbb.requestBusinessParameter = new JSONObject();// "需要你自定义的JSONObject格式的参数";
//		rb = rb.ba.operateDB(rb);
//		JSONObject jo6_b = JSON.parseObject(rb.dealBack);
//		String count = Util_json.getValueByKey(jo6_b, "count");//
////事件反馈
//		JSONObject jo4 = new JSONObject();
//		jo4.put("pageNumber", "0");
//		jo4.put("lines", "5");
//		jo4.put("question", "");
//		jo4.put("questionType", "2");
//		rb.rbb.requestBusiness = "s_questions_select_getAllImport";
//		rb.rbb.requestBusinessParameter = jo4;// "需要你自定义的JSONObject格式的参数";
//		rb = rb.ba.operateDB(rb);
//		JSONArray ja4 = JSONArray.parseArray(rb.dealBack);

        hs.put("current_overhaul_info", overhaulLibrary);
        hs.put("dose_value_monitor", list0);
        hs.put("stage_orderno_number", stage_orderno_number);
        hs.put("orderno_start_number", orderno_start_number);
        hs.put("current_stage_name", stage_name);
        hs.put("stage", list);
        hs.put("orders", list2);
        hs.put("dose_value_info", jas);
        hs.put("changeType", changeType);// 1上升2下降3不变
        hs.put("changeRate", changeRate);
        hs.put("today_doseValue", today_doseValue);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    //  查询所有大修name
    @RequestMapping("/getAllOverhaul")
    public String getAllOverhaul() throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        List<OverhaulLibrary> overhaulLibraries = overhaulLibraryService.selectOverhaulLibraryList(null);
        hs.put("overhaulLibList", overhaulLibraries);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    //  查询所有大修阶段
    @RequestMapping("/getAllstageByOverhaul")
    public String getAllstageByOverhaul(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        iOverhaulStageService.getAllByOverhaul((String) json.get("current_overhaul"), hs);
        return objectMapper.writeValueAsString(hs);

    }

    @RequestMapping("/export")
    public AjaxResult export(HttpServletResponse response, @RequestParam Map<String, Object> param) throws IllegalAccessException, IOException, InstantiationException {
        HashMap<String, Object> hs = new HashMap<>();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        List<SQuestions> list = sQuestionsService.getAllQuestionsExport((String) json.get("questionType"), (String) json.get("begin_time"), (String) json.get("end_time"));
        //设置响应头和编码
//        ExcelUtils.setResponse(response, "优化建议");
        //给定导出类，导出数据，工作表名称，样式
//        ExcelUtils.export(response, SQuestions.class, list, "优化建议", ExcelUtils.getStyleStrategy());
        ExcelUtil<SQuestions> util = new ExcelUtil<SQuestions>(SQuestions.class);
        return util.exportExcel(list, "优化建议");
    }

    //  事件类型查询
    @RequestMapping("/getConfigs")
    public String getConfigs(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        sDictionaryService.selectSDictionaryByCodeType((String) json.get("codeType"), hs);
        return objectMapper.writeValueAsString(hs);
    }

    //  查询我的录入
    @RequestMapping("/getMyQuestions")
    public String getMyQuestions(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
//        {"pageNumber":0,"lines":10,"questionType":"2","add_user":""}
        sQuestionsService.getMyQuestions((Integer) json.get("pageNumber"), (Integer) json.get("lines"), (String) json.get("questionType"), (String) json.get("add_user"), hs);
        return objectMapper.writeValueAsString(hs);
    }

    //    查询全部录入
    @RequestMapping("/getAllQuestions")
    public String getAllQuestions(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        sQuestionsService.getAllQuestions((Integer) json.get("pageNumber"), (Integer) json.get("lines"), (String) json.get("questionType"), (String) json.get("begin_time"), (String) json.get("end_time"), hs);
        return objectMapper.writeValueAsString(hs);
    }

    @RequestMapping("/feadback")
    public String feadback(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
//获取入参
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String questions_id = (String) json.get("questions_id");
        String discuss_id = (String) json.get("discuss_id");
        String user_id = (String) json.get("user_id");
        String contents = (String) json.get("contents");
        String scores = (Integer) json.get("scores")+"";
        String type = (String) json.get("type");

        int sqCount = 0;
        if ("discuss".equals(type)) {
            SQuestionsDiscuss sd = new SQuestionsDiscuss();
            sd.setId(UUID.randomUUID().toString());
            sd.setQuestionsId(questions_id);
            sd.setAddUserId(user_id);
            sd.setContents(contents);
            sd.setScores(scores);
            sd.setAddTimes(new Date());
            sqCount = iSQuestionsDiscussService.insertSQuestionsDiscuss(sd);
        } else if ("replay".equals(type)) {
            SQuestionsDiscussReplay sdp = new SQuestionsDiscussReplay();
            sdp.setId(UUID.randomUUID().toString());
            sdp.setQuestionsId(questions_id);
            sdp.setDiscussId(discuss_id);
            sdp.setAddUserId(user_id);
            sdp.setContents(contents);
            sdp.setAddTimes(new Date());
            sqCount = iSQuestionsDiscussReplayService.insertSQuestionsDiscussReplay(sdp);
        }
        if (sqCount > 0) {
            hs.put("code", 0);
            hs.put("msg", "提交成功");
        } else {
            hs.put("code", 1);
            hs.put("msg", "提交失败");
        }
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 简洁模式提交
     *
     * @param param
     * @return
     */
    @RequestMapping("/addQuestionsSuccinct")
    public String addQuestionsSuccinct(@RequestParam Map<String, Object> param) throws JsonProcessingException {
//        {"protectScores":10,"question":"","fileUrls":"","add_user":""}
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        String fileUrls = (String) json.get("fileUrls");
        SQuestions sQuestions = new SQuestions();
        String id = UUID.randomUUID().toString();
        sQuestions.setId(id);
        sQuestions.setProtectScores(Integer.toString((Integer) json.get("protectScores")));
        sQuestions.setQuestion((String) json.get("question"));
        sQuestions.setAddUser((String) json.get("add_user"));
        sQuestions.setTitle("");
        sQuestions.setStatuss("1");
        sQuestions.setSuggest("");
        sQuestions.setIncome("");
        sQuestions.setQuestionType("2");
        sQuestions.setKeyInType("2");
        sQuestions.setIsTarget("N");
        sQuestions.setThingsType("");
//        sQuestions.setQuestionTimes("");
        sQuestions.setOverhaulName("");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String addTime = LocalDateTime.now(ZoneOffset.of("+8")).format(df);
        sQuestions.setAddTime(addTime);
        int sqCount = sQuestionsService.insertSQuestions(sQuestions);
        int imgCount = 0;
        if (fileUrls.length() > 0) {
            String[] fs = fileUrls.split(",");
            for (int i = 0; i < fs.length; i++) {
                SImages images = new SImages();
                images.setId(UUID.randomUUID().toString());
                images.setQuestionsId(id);
                images.setFileUrl(fs[i]);
                images.setOrderNumbers(i + 1 + "");
                imgCount = imagesService.insertSImages(images);
            }
        }
        hs.put("code", 1);
        hs.put("msg", "提交失败");
        if (sqCount > 0 || imgCount > 0) {
            hs.put("code", 0);
            hs.put("msg", "提交成功");
        }
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        if (file.isEmpty()) {
            hs.put("code", 1);
            hs.put("msg", "上传失败，请选择文件");
            hs.put("url", "");
            return mapper.writeValueAsString(hs);
        }

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();

        String fileName = FileUploadUtils.upload(filePath, file);
        String url = ServerConfig.getUrl() + fileName;

//        String fileName = file.getOriginalFilename();
//        File dest = new File(filePath + fileName);
//        // 文件目录不存在就创建文件
//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdirs();
//        }
//        try {
//            file.transferTo(dest);
            hs.put("code", 0);
            hs.put("msg", "文件上传成功");
            hs.put("url", url);
//        } catch (IOException e) {
//            hs.put("code", 1);
//            hs.put("msg", "上传失败，请选择文件");
//            hs.put("url", "");
//        }
        return mapper.writeValueAsString(hs);
    }

    //  查询在线人员
    @RequestMapping("/getOnline")
    public String getOnline(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        int pageNumber = (Integer) json.get("pageNumber");
        int lines = (Integer) json.get("lines");
        trafficRecordService.getAllOnline(pageNumber, lines, hs);
        return objectMapper.writeValueAsString(hs);
    }

    @RequestMapping("/getOrders")
    public String getOrders(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        trafficRecordService.getAllOrders(hs);
        return objectMapper.writeValueAsString(hs);
    }

    @RequestMapping("/getOrderInfo")
    public String getOrderInfo(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        int TR_ID = (Integer) json.get("TR_ID");
        List<TrafficRecord> tr = trafficRecordService.getOrderInfo(TR_ID, hs);
        hs.put("TrafficRecord", tr);
        hs.put("code", 0);
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 异常录入
     *
     * @param param
     * @return
     */
    @RequestMapping("/addEstimated")
    public String addEstimated(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        EstimatedEvent estimatedEvent = new EstimatedEvent();
        estimatedEvent.setOverhaulName((String) json.get("overhaul_name"));
        estimatedEvent.setTheme((String) json.get("theme"));
        estimatedEvent.setEventContent((String) json.get("event_content"));
        estimatedEvent.setEnteredBy((String) json.get("entered_by"));
        estimatedEvent.setEventType((String) json.get("event_type"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String eventTime = LocalDateTime.now(ZoneOffset.of("+8")).format(df);
        estimatedEvent.setEventTime(eventTime);
        int count = estimatedEventService.insertEstimatedEvent(estimatedEvent);
        if (count > 0) {
            hs.put("code", 0);
            hs.put("msg", "添加成功");
        }
        return objectMapper.writeValueAsString(hs);
    }

    @RequestMapping("/getMyEstimated")
//    {"pageNumber":0,"lines":20,"entered_by":""}
    public String getMyEstimated(@RequestParam Map<String, Object> param) throws JsonProcessingException {
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = (String) param.get("parameter");
        JSONObject json = JSONObject.parseObject(jsonStr);
        System.out.println(json.get("pageNumber"));
        estimatedEventService.getMyEstimated((Integer) json.get("pageNumber"), (Integer) json.get("lines"), (String) json.get("entered_by"), hs);
        return objectMapper.writeValueAsString(hs);
    }

    public static JSONArray jsonArraySort(JSONArray array, final String sortColName, final boolean isAsc) {
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonList = new ArrayList<JSONObject>();
        for (int i = 0; i < array.size(); i++) {
            jsonList.add(array.getJSONObject(i));
        }

        // 将 JSONArray 转换成 List,本质上还是对 List 进行排序
        Collections.sort(jsonList, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String valA = o1.getString(sortColName);
                String valB = o2.getString(sortColName);
                BigDecimal DobA = new BigDecimal(valA);
                BigDecimal DobB = new BigDecimal(valB);
                if (isAsc) {
                    // 升序
                    return DobA.compareTo(DobB);
                } else {
                    return DobB.compareTo(DobA);
                }
            }
        });
        // 此时jsonList已经是排完序的集合了
        for (JSONObject obj : jsonList) {
            sortedJsonArray.add(obj);
        }
        return sortedJsonArray;
    }
}
